package com.xuecheng.media.config;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.vod.model.v20170321.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import javax.annotation.PostConstruct;

@Component
public class VodTemplate {

    @Autowired
    private AliyunProperties prop;

    private DefaultAcsClient client;


    // 初始化client
    @PostConstruct
    public void init() {
        DefaultProfile profile = DefaultProfile.getProfile(
                prop.getRegion(),
                prop.getAccessKeyId(),
                prop.getAccessKeySecret());
        client = new DefaultAcsClient(profile);
    }


    /**
     * 获取视频上传地址和凭证
     * @param fileTitle 流媒体文件的显示名称
     * @param fileName  流媒体文件的原始名称
     * @return CreateUploadVideoResponse 获取视频上传地址和凭证响应数据
     */
    public CreateUploadVideoResponse createUploadVideo(String fileTitle, String fileName) throws Exception {
        CreateUploadVideoRequest request = new CreateUploadVideoRequest();
        request.setTitle(fileTitle);
        request.setFileName(fileName);
        return client.getAcsResponse(request);
    }


    /**
     * 刷新视频上传凭证
     * @return RefreshUploadVideoResponse 刷新视频上传凭证响应数据
     */
    public RefreshUploadVideoResponse refreshUploadVideo(String videoId) throws Exception {
        RefreshUploadVideoRequest request = new RefreshUploadVideoRequest();
        request.setVideoId(videoId);
        return client.getAcsResponse(request);
    }


    /**
     * 获得媒资播放请求对象
     */
    public GetPlayInfoResponse getPlayInfo(String videoId) throws Exception {
        GetPlayInfoRequest request = new GetPlayInfoRequest();
        request.setVideoId(videoId);
        return client.getAcsResponse(request);
    }


    /**
     * 删除视频
     * @param videoIds 流媒体文件的fileId值
     * @return DeleteVideoResponse 删除视频响应数据
     * @throws Exception
     */
    public void deleteVideo(String... videoIds) throws Exception {
        DeleteVideoRequest request = new DeleteVideoRequest();
        if (ObjectUtils.isEmpty(videoIds)) {
            return ;
        }
        //支持传入多个视频ID，多个用逗号分隔
        String videoIdsStr = String.join(",", videoIds);
        request.setVideoIds(videoIdsStr);
        client.getAcsResponse(request);
    }
}